# 初始化MongoDB客户端
from bson import ObjectId
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')  # 默认连接本地MongoDB
db = client['test']  # 使用test数据库
book_collection = db['book']  # 使用book集合
hot_book_collection = db['hot_books']
def featured_recommendations(id):
    # 1. 从 hot_book_collection 中随机抽取 10 本书
    random_books = hot_book_collection.aggregate([
        {'$sample': {'size': 10}}
    ])

    # 2. 获取热门图书 ID 列表
    hot_book_ids = [book['b_id'] for book in random_books]

    if not hot_book_ids:
        return []

    # 3. 根据 ID 列表从 book 集合获取图书信息
    books = list(book_collection.aggregate([
        {"$match": {"_id": {"$in": [ObjectId(bid) for bid in hot_book_ids]}}}
    ]))

    # 4. 合并分析数据和图书详情
    recommendations = []
    for book in books:
        recommendations.append({
            '_id': str(book['_id']),
            'title': book['title'],
            'author': book['author'],
            'cover': book['cover']
        })

    return recommendations